package shayu.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import dm.jdbc.util.StringUtil;
import io.renren.common.to.mq.SeckillOrderTo;
import io.renren.common.utils.R;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import shayu.seckill.feign.CouponFeign;
import shayu.seckill.feign.ProductFeign;
import shayu.seckill.service.SeckillService;
import shayu.seckill.to.SeckillSkuRedisTo;
import shayu.seckill.vo.SeckillSesssionWithSkus;
import shayu.seckill.vo.SkuInfoVo;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeign productFeign;

    @Autowired
    private CouponFeign couponFeign;

    @Autowired
    private RedissonClient redissonClient;

    private final String SESSION_CACHE_PERFIX = "seckill:session:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";// +商品随机码

    private final String token = UUID.randomUUID().toString().replace("-", "");


    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 1.扫描最近三天需要参与的秒杀活动
        R session = couponFeign.getLates3DaySession();
        if (session.getCode() == 0) {
            List<SeckillSesssionWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSesssionWithSkus>>() {
            });

            // 缓存到reids中
            // 1.缓存活动信息
            saveSessionInfos(sessionData);
            // 2. 缓存活动的关联商品信息
            saveSessionSkuInfo(sessionData);


        }
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentAeckillSkus() {
        // 1.确定当前那个场次
        long currentTimeMillis = System.currentTimeMillis();
        // 查询Redis中所有keyy以seckill：session开头的所有数据
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PERFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSION_CACHE_PERFIX, "");
            String[] s = replace.split("_");
            // 获取存入redis商品的开始时间和结束时间
            long startTime = Long.parseLong(s[0]);
            long endTime = Long.parseLong(s[1]);
            // 2.获取这个场次需要的所有商品信息
            if (currentTimeMillis >= startTime && currentTimeMillis <= endTime) {
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SKU_STOCK_SEMAPHORE);
                List<Object> list = hashOps.multiGet(Collections.singleton(range));
                if (list != null) {
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        String items = (String) item;
                        SeckillSkuRedisTo redisTo = JSON.parseObject(items, SeckillSkuRedisTo.class);
                        // 秒杀开始需要随机码
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        // 1.找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            // 使用正则表达式
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo skuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);

                    // 随机码
                    long current = new Date().getTime();
                    Long startTime = skuRedisTo.getStartTime();
                    Long endTime = skuRedisTo.getEndTime();
                    // 如果当前时间大于等于活动秒杀开始时间并且要小于活动结束时间
//                    if (current >= startTime && current <= endTime) {
//                        String randomCode = skuRedisTo.getRandomCode();
//                        String s = skuRedisTo.getPromotionSessionId() + "_" + skuRedisTo.getSkuId();
//                        if(randomCode.equals(key)&&)
//
//                    } else {
//                        skuRedisTo.setRandomCode(null);
//                    }
                    return skuRedisTo;
                }
            }
        }
        return null;
    }

    // 删掉秒杀活动
    @Override
    public String kill(String killId, String key, Integer num) throws InterruptedException {
        // 1. 获取当前秒杀商品的详情信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtil.isEmpty(json)) {
            return null;
        } else {
            // 校验合法性
            SeckillSkuRedisTo skuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            Long startTime = skuRedisTo.getStartTime();
            Long endTime = skuRedisTo.getEndTime();
            long time = new Date().getTime();
            if (time >= startTime && time <= endTime) {
                String randomCode = skuRedisTo.getRandomCode();
                String skuId = skuRedisTo.getPromotionSessionId() + "_" + skuRedisTo.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    // 3.验证购物是否合理
                    Integer seckillLimit = skuRedisTo.getSeckillLimit();
                    // 获取信号量
                    String seckillCount = redisTemplate.opsForValue().get(SKU_STOCK_SEMAPHORE);
                    Integer count = Integer.valueOf(seckillCount);
                    if (count > 0 && num <= seckillLimit && count > num) {

                        // 4. 验证这个人是否购买过
                        String redisKey = skuRedisTo.getId() + "_" + skuId;
                        // 自动过期
                        long ttl = endTime - time;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MINUTES);
                        if (aBoolean){
                            // 占位成功说明没有购买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE);
                            boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MINUTES);
                            // 成功
                            // 快速下单 给MQ发消息
                            String timeId = IdWorker.getTimeId();
                            SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                            seckillOrderTo.setOrderSn(timeId);
                            seckillOrderTo.setNum(num);
                            seckillOrderTo.setPromotionSessionId(seckillOrderTo.getPromotionSessionId());
                            seckillOrderTo.setSeckillPrice(seckillOrderTo.getSeckillPrice());
                            seckillOrderTo.setSkuId(skuRedisTo.getSkuId());
                            seckillOrderTo.setSeckillPrice(skuRedisTo.getSeckillPrice());
                            redisTemplate.convertAndSend("order-event-ex change","order.seckill.order");

                            return timeId;
                        }else{
                            // 说明已经购买过了
                            return null;
                        }
                    }
                }
            } else {
                return null;
            }
        }
        return null;
    }

    /**
     * 缓存秒杀活动所关联的商品信息
     */
    private void saveSessionSkuInfo(List<SeckillSesssionWithSkus> sessions) {
        sessions.stream().forEach(sesssion -> {
            // 准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            sesssion.getRelationSkus().forEach(seckillSkuVo -> {
                // 生成随机码
                String redisKey = seckillSkuVo.getPromotionSessionId().toString().replace("-", "");
                if (!ops.hasKey(redisKey)) {
                    // 缓存商品
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    // 1. sku基本数据
                    R skuInfo = productFeign.getSkuInfo(redisTo.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(info);
                    }

                    // 2. sku秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTo);

                    // 3. 设置上当前商品的秒杀时间设置
                    redisTo.setStartTime(sesssion.getCreateTime().getTime());
                    redisTo.setEndTime(sesssion.getEndTime().getTime());

                    // 4. 随机码(防止恶意攻击)
                    redisTo.setRandomCode(token);

                    // 序列化到redis中
                    String JsonString = JSON.toJSONString(redisTo);
                    ops.put(seckillSkuVo.getId(), JsonString);

                    // 5. 使用库存作为分布式的信号量 限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    // 商品可以秒杀的数量作为信号量
                    semaphore.trySetPermitsAsync(seckillSkuVo.getSeckillCount());


                }
            });
        });
    }

    // 缓存秒杀信息
    private void saveSessionInfos(List<SeckillSesssionWithSkus> sesssions) {
        sesssions.stream().forEach(sesssion -> {
            // 获取当前时间戳
            long startTime = sesssion.getCreateTime().getTime();
            long endTime = sesssion.getEndTime().getTime();
            // 存入到Redis中的key
            String key = SESSION_CACHE_PERFIX + startTime + "_" + endTime;
            // 判断Redis中是否有该信息，如果没有才添加
            Boolean hasKey = redisTemplate.hasKey(key);
            // 缓存活动信息
            if (!hasKey) {
                List<String> skuIds = sesssion.getRelationSkus().stream().map(item ->
                        item.getPromotionSessionId() + "-" + item.getId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, skuIds);
            }
        });
    }

//    // TODO 未写
//    private void saveSessionSkuInfos(List<SeckillSesssionWithSkus> sesssions){
//        sesssions.stream().forEach(sesssion -> {
//            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX + sesssion);
//            sesssion.getRelationSkus().stream().forEach(seckillSkuVo -> {
//                if(!ops.hasKey(seckillSkuVo.getSkuId().toString())){
//
//                }
//                if(!redisTemplate.hasKey(SKU_STOCK_SEMAPHORE+token)){
//                    // 5. 使用库存作为分布式的信号量 限流
//                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
//                    // 商品可以秒杀的数量作为信号量
//                    semaphore.trySetPermitsAsync(seckillSkuVo.getSeckillCount());
//                }
//            });
//        });
//    }
}
